[1] 2
Writing functions in R
A community-driven R package

takes input –> does something –> returns output
subtract <- function(arg1, arg2) {
arg1 - arg2
}
Imagine calculating the mean without standard functions like mean or sum:
Arguments need to be provided in the correct order, or specified by name:
Make function use more convenient, can hide complexities.
Additional, optional arguments can be allowed by using ‘…’ as the last argument:
A function generally should return something, but this does not:
Return explicitly with return, or place return value at the end of the function:
This did not work as intended. R functions only return one object. Instead use lists or other data structures:
Custom binary operators – let’s define an operator for “not in”:
if a condition is true, do something.
else instructs what to do when the if condition is not met.
Instead of many if and else statements, try switch
Loops are used for repeating similar actions multiple times. for loops iterate over a set of values. The iterator (i) changes with every iteration of the loop:
To generate sequences of integers, we can use seq_len. Let’s make a function:
while loops repeat a task until a condition is no longer met.
Create a function that can sort a data.frame into latitudinal bins. That is, we want a new column that identifies the bin of each entry of the data set. As an exemplary data set, we can use the reefs data from palaeoverse.
If you are new to writing R functions, try a simpler function that can sort data into the northern and southern hemisphere.
Here is what the result may look like when sorted into hemispheres:
Give variables and functions consistent names. These are the two most common styles:
Common practices:
Example of a detailed style guide: Tidyverse’s style guide
Add some general information in the beginning of a large R script.
### Change point regression analysis
### July 2021
### Kilian Eichenseer
###
### Bayesian algorithm for finding a change point in
### the linear relationship between two variables.
### Uses JAGS (https://mcmc-jags.sourceforge.io/).
### Generate the data
set.seed(10)
n <- 60 # number of total data points… or use proper documentation
install.packages("roxygen2")’#This could generate documentation for the subtract function from earlier:
Comments
Good code needs less comments - but comment enough that you can still use your code two years later.